const userid = require('userid')
const pry = require('pryjs')

function uid (user) {
  try {
    if (typeof(user) === 'number') {
      return userid.username(user) && user
    } else if (typeof(user) === 'string') {
      return userid.uid(user)
    } else {
      throw new ExecuteResolveError(`user参数(${user})必须是数字或字符串类型`)
    }
  } catch (err) {
    if (err.message === 'username not found' || err.message === 'uid not found') {
      throw new ExecuteResolveError(`不存在的用户：${user}。`)
    } else {
      throw err
    }
  }
}

function gid (group) {
  try {
    if (typeof(group) === 'number') {
      return userid.groupname(group) && group
    } else if (typeof(group) === 'string') {
      return userid.gid(group)
    } else {
      throw new ExecuteResolveError(`group(${group})必须是数字或字符串类型`)
    }
  } catch (err) {
    if (err.message === 'groupname not found' || err.message === 'gid not found') {
      throw new ExecuteResolveError(`不存在的用户组：${group}。`)
    } else {
      throw err
    }
  }
}

class ExecuteResolveError extends Error {}

exports.uid = uid
exports.gid = gid
exports.ExecuteResolveError = ExecuteResolveError
